package cn.dgut.jy.soro.service.impl;

import cn.dgut.jy.soro.entity.CartItem;
import cn.dgut.jy.soro.repository.CartItemRepository;
import cn.dgut.jy.soro.repository.CartRepository;
import cn.dgut.jy.soro.repository.UserRepository;
import cn.dgut.jy.soro.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    private CartRepository cartRepository;
    private UserRepository userRepository;
    private CartItemRepository cartItemRepository;

    @Autowired
    public CartServiceImpl(CartRepository cartRepository, UserRepository userRepository,
                           CartItemRepository cartItemRepository) {
        this.cartRepository = cartRepository;
        this.userRepository = userRepository;
        this.cartItemRepository = cartItemRepository;
    }


    @Override
    public List<CartItem> getCartItemsByUserId(Integer userId) {
        if(userRepository.findById(userId).isPresent()) {
            return cartItemRepository.findByCartId(userRepository.findById(userId).get().getCart_id());
        }
        return null;
    }

    @Override
    public Float getTotalPriceByUserId(Integer userId) {
        return cartRepository.findByUserId(userId).getTotalPrice();
    }

    @Override
    public List<CartItem> getCartItemsByUserIdAndProductIds(Integer userId, Integer[] productIds) {

        if(!userRepository.findById(userId).isPresent()) {
            return null;
        }

        Integer cartId = userRepository.findById(userId).get().getCart_id();

        List<CartItem> cartItems = new LinkedList<>();
        for (Integer productId : productIds
             ) {
            cartItems.add(cartItemRepository.findByCartIdAndProductId(cartId, productId));
        }

        return  cartItems;

    }
}
